import storage from '@/util/storage'
import useRouteStore from './route'
import useMenuStore from './menu'
import { getRoleBtnListApi } from '@/api/auth'

const useUserStore = defineStore(
  // 唯一ID
  'user',
  {
    state: () => ({
      account: localStorage.account || '',
      token: storage.local.get('token') || '',
      failure_time: localStorage.failure_time || '',
      permissions: [],
      btnPermissions: [],
      keycloak: {},
      userInfo: storage.local.get('userInfo') || {},
      classInfo: {}
    }),
    getters: {
      isLogin: state => {
        let result = false
        if (state.token || state.keycloak.authenticated) {
          result = true
        }
        return result
      }
    },
    actions: {
      SET_TOKEN(data) {
        this.token = data
      },
      SET_USER_INFO(data) {
        this.userInfo = data
        this.account = data.account
        storage.local.set('account', data.account)
        storage.local.set('userInfo', data)
      },
      login() {
        return new Promise(() => {
          // 登录
        })
      },
      setKeycloak(data) {
        this.keycloak = data
      },
      logout() {
        return new Promise(resolve => {
          const routeStore = useRouteStore()
          const menuStore = useMenuStore()
          routeStore.removeRoutes()
          menuStore.setActived(0)
          resolve()
        })
      },
      // 获取我的权限
      getPermissions() {
        return new Promise(resolve => {
          getRoleBtnListApi().then(rst => {
            this.btnPermissions = rst
            resolve(this.btnPermissions)
          }).catch(() => {})
        })
      }
    }
  }
)

export default useUserStore
